import Axios from 'axios'
import { ElNotification } from 'element-plus'
import 'element-plus/es/components/notification/style/css'
Axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API
Axios.defaults.timeout = 60000
Axios.interceptors.response.use(
  (res: any) => {
    const useTip = res.config?.useCommonTip
    if (res.data?.code === 200) {
      if (useTip) {
        ElNotification({
          title: '成功！',
          message: res.data.message,
          type: 'success'
        })
        return res.data.data
      }
      return res.data
    }
    if (res.data?.code === 402) {
      setTimeout(() => {
        window.location.reload()
      }, 3000)
    }
    ElNotification({
      title: '错误',
      message: res.data?.message,
      type: 'error'
    })
    return Promise.reject(res.data)
  },
  (err) => {
    if (err.status >= 400 && err.status < 500) {
      if (err.response?.data?.message) {
        ElNotification.warning(err.response.data.message)
        return Promise.resolve(err.response.data.message)
      }
    }
    ElNotification.error('服务器错误请联系管理员！')
    return Promise.reject(err)
  },
)
Axios.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) { // 存在token
    config.headers = {
      Authorization: `Bearer ${token}`
    } as any
  }
  
  return config
})
export default Axios
